import { login, getUserInfo, logout  } from "@/api/doubaoApi";
import { getToken, setToken, removeToken } from "@/utils/auth";

//定义vuex的全局数据但是一刷新页面就没有了
const state = {
    token: getToken(), // 从cookie中读取到的token
    user: "", // 用户对象
};
//state里状态的改变必须通过mutations并且里面不能调异步的方法
const mutations = {
    SET_TOKEN_STATE: (state, token) => {
        state.token = token
    },
    SET_USER_STATE: (state, user) => {
        state.user = user
    },
};
//异步的方法在actions里定义
const actions = {
    // 用户登录的时候把userInfo提交给mutations
    login({ commit }, userInfo) {
        console.log(userInfo)
        //从用户信息里拿出name,pass,rememberMe字段
        const { name, pass, rememberMe } = userInfo
        return new Promise((resolve, reject) => {
            //调用login接口向服务器发请求的，then接收服务器的回应
            login({ username: name.trim(), password: pass, rememberMe: rememberMe }).then(response => {
                const { data } = response
                //将此处服务器返回的token放到mutations中的token
                commit('SET_TOKEN_STATE', data.token)
                //此处又保存到js-cookie中一天
                setToken(data.token)
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },
    // 获取用户信息
    getInfo({ commit, state }) {
        return new Promise((resolve, reject) => {
            //调用getUserInfo接口向服务器发请求的，then接收服务器的回应
            getUserInfo().then(response => {
                const { data } = response
                console.log("用户信息")
                console.log(data);
        
                if (!data) {
                    commit('SET_TOKEN_STATE', '')
                    commit('SET_USER_STATE', '')
                    removeToken()
                    resolve()
                    reject('Verification failed, please Login again.')
                }
                //将此处服务器返回的data放到mutations中的user
                commit('SET_USER_STATE', data)
                resolve(data)
            }).catch(error => {
                reject(error)
            })
        })
    },
    // 注销
    logout({ commit, state }) {
        return new Promise((resolve, reject) => {
            logout(state.token).then((response) => {
                console.log(response);
                //把vuex中state清空
                commit("SET_TOKEN_STATE", "");
                commit("SET_USER_STATE", "");
                //把js-cookie清空
                removeToken();
                resolve();
            })
            .catch((error) => {
                reject(error);
            });
        });
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
